//package newsSystem.utils;
//import java.sql.Connection;
//import java.sql.DriverManager;
//import java.sql.Statement;
//
//public class JDBC {
//    public static void main(String[] args) throws Exception {
////        //1. 注册驱动,可以不使用
////        Class.forName("com.mysql.cj.jdbc.Driver");
////        //2. 获取连接对象
////        String url = "jdbc:mysql://localhost:3306/newssubsystem";
////        String username = "root";
////        String password = "123456";
////        Connection connection = DriverManager.getConnection(url, username, password);
//
//    }
//}
package newsSystem.utils;
import java.sql.*;

public class DBUtil {
    private static final String URL = "jdbc:mysql://localhost:3306/newssubsystem";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

//    封装工具类，连接数据库，DBUtil.getConnection() 来获取数据库连接，而无需重复编写连接数据库的代码。
    public static Connection getConnection() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }
//封装 DBUtil.closeConnection() 方法，也可以更方便地释放资源，避免代码重复。
    public static void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
//    释放数据库的State对象
    public static void closePreparedStatement(Statement Statement) {
        if (Statement != null) {
            try {
                Statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
//释放数据库结果集合的封装类
public static void closeResultSet(ResultSet resultSet) {
    if (resultSet != null) {
        try {
            resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
}
